package dao

import (
	"github.com/astaxie/beego/orm"
	"xiaoercaidan/publicResources/models"
	"xiaoercaidan/publicResources/utils"
	"strconv"
	"time"
	"math/rand"
	"fmt"
)

func InserUserToken(token *models.UserToken) (error) {

	o := orm.NewOrm()

	_id, err := o.Insert(token)

	token.Id = _id

	return err
}

func DeleteUserToken(token *models.UserToken) (error) {

	o := orm.NewOrm()

	_, err := o.Delete(token)

	return err
}

func UpdateUserToken(token *models.UserToken) (error) {

	o := orm.NewOrm()

	_, err := o.QueryTable("user_token").Filter("id", token.Id).Update(orm.Params{
		"last_login_time": token.LastLoginTime,
		"token": token.Token,
	})

	return err
}

func QueryUserToken(userId int64) (*models.UserToken) {

	o := orm.NewOrm()

	var token models.UserToken

	var qs orm.QuerySeter

	qs = o.QueryTable("user_token")

	qs = qs.Filter("user_id" + "__icontains", userId)

	qs.One(&token)

	return &token

}


func QueryOrCreateUserToken(userId int64) (string) {

	token := QueryUserToken(userId)

	fmt.Println(token)

	if (token == nil || token.Id <= 0) {

		fmt.Println(token)

		token = new(models.UserToken)

		token.Token = utils.Md5(strconv.FormatInt(userId, 10) + strconv.FormatInt(time.Now().Unix(), 10) + strconv.Itoa(rand.Intn(100000)))

		token.LastLoginTime = time.Now().Unix()

		token.UserId = userId

		InserUserToken(token)

	}

	return token.Token

}
